// 系统模块加载器
import { registerApp } from '@mf/utils'
import axios from 'axios'
import init, { run } from 'rust'
import { start } from 'single-spa'

interface ProjectConfig {
    success: boolean
    data: {
        list: any[]
    }
}

const startProject = (projects: any[] = []) => {
    try {
        registerApp(projects)
        start()
    } catch (error) {
        console.error('Failed to start project:', error)
    }
}

const loadProjects = async () => {
    const { projectConfigUrl } = window.AppConfig

    try {
        if (!projectConfigUrl) {
            return startProject()
        }

        if (projectConfigUrl.match(/\.(js)$/)) {
            const projects = await window.System.import(`${projectConfigUrl}?${Date.now()}`)
            return startProject(projects.default)
        }

        const { data: response } = await axios.get<ProjectConfig>(`${projectConfigUrl}?${Date.now()}`)
        if (response.success) {
            startProject(response.data.list)
        } else {
            console.warn('Failed to load projects:', response)
        }
    } catch (error) {
        console.error('Error loading projects:', error)
        startProject() // 加载失败时使用空项目列表
    }
}
const initialize = async () => {
    try {
        // @ts-ignore
        await init.default()
        await run('')
        await loadProjects()
    } catch (error) {
        console.error('Initialization failed:', error)
    }
}

initialize()
